package com.api.oa.services.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.api.oa.common.UserType;
import com.api.oa.config.EmServer;
import com.api.oa.config.UserContext;
import com.api.oa.mapper.YQMedCareMapper;
import com.api.oa.mapper.YQPatientMapper;
import com.api.oa.mapper.YQUserMapper;
import com.api.oa.model.entity.YQMedCare;
import com.api.oa.model.entity.YQPatient;
import com.api.oa.model.entity.YQUser;
import com.api.oa.model.vo.UserInfoVO;
import com.api.oa.model.vo.YQContacts;
import com.api.oa.services.YQUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;


@Service
public class YQUserServiceImpl implements YQUserService {

    @Autowired
    private YQUserMapper mapper;
    @Autowired
    private YQMedCareMapper yqMedCareMapper;
    @Autowired
    private YQPatientMapper yqPatientMapper;


    @Autowired
    private EmServer emServer;

    @Override
    public Integer add(YQUser entity) {
        entity.setStatus(0);
        entity.setCreatedAt(DateUtil.date());
        if (UserContext.getRole() == UserType.INS) {
            entity.setBelongInsCode(UserContext.getInsCode());
        }
        entity.setPasswd(SecureUtil.md5(entity.getPasswd()));
        return mapper.insert(entity);
    }

    @Override
    public void remove(Long id) {
        mapper.delete(id);
    }

    @Override
    public Integer update(YQUser entity) {
        return mapper.update(entity);
    }

    @Override
    public PageInfo<YQUser> list(String insCode, String role, String account, Integer pageIndex, Integer pageSize) {
        if (UserContext.getRole() == UserType.INS) {
            insCode = UserContext.getInsCode();
        }
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc,userId desc");
        return new PageInfo<>(mapper.list(insCode, role, account));
    }

    @Override
    public YQUser one(Long id) {
        return mapper.findOne(id);
    }


    @Override
    public YQUser login(String account, String passWord) throws Exception {
        YQUser oneByAccount = mapper.findOneByAccount(account);
        if (oneByAccount == null) {
            throw new Exception("用户不存在");
        }
        if (!oneByAccount.getPasswd().equals(SecureUtil.md5(passWord))) {
            throw new Exception("密码错误");
        }


        return oneByAccount;
    }

    @Override
    public YQUser register(String account, String passwd, Integer role) throws Exception {
        YQUser oneByAccount = mapper.findOneByPhone(account);
        if (oneByAccount != null) {
            throw new Exception("用户已经存在");
        }
        YQUser yqUser = new YQUser();
        yqUser.setPhone(account);
        yqUser.setUserType(role);
        yqUser.setCreatedAt(DateUtil.date());
        yqUser.setPasswd(SecureUtil.md5(passwd));
        mapper.insert(yqUser);
        return yqUser;
    }

    @Override
    public UserInfoVO info() {
        UserInfoVO userInfoVO = new UserInfoVO();
        YQUser one = mapper.findOne(UserContext.getUserId());
        userInfoVO.setRoles(new int[]{one.getUserType()});
        if (one.getUserType() < 3) {
            YQMedCare one1 = yqMedCareMapper.findOne(one.getUserId());
            userInfoVO.setAvatar(one1.getMedFace());
            userInfoVO.setName(one1.getMedName());
        } else if (one.getUserType() == 3) {
            YQPatient one1 = yqPatientMapper.findOne(one.getUserId());
            userInfoVO.setAvatar(one1.getPatientFace());
            userInfoVO.setName(one1.getPatientName());
        } else {
            userInfoVO.setName(one.getUname());
        }
        return userInfoVO;
    }

    @Override
    public List<YQUser> assUser(String insCode, Integer role) {
        if (UserContext.getRole() == UserType.INS) {
            insCode = UserContext.getInsCode();
            role = UserType.INS_ASS;
        } else if (UserContext.getRole() == UserType.GOV) {
            role = UserType.GOV_ASS;
        }
        return mapper.assUsers(insCode, role);
    }

    @Override
    public Integer resetPwd(Long account, String org, String passwd) throws Exception {
        YQUser oneByAccount = mapper.findOne(account);
        if (oneByAccount == null) {
            throw new Exception("用户不存在");
        }
        String s = SecureUtil.md5(org);
        if (!s.equals(oneByAccount.getPasswd())) {
            throw new Exception("密码不正确");
        }
        return mapper.updatePwd(account, SecureUtil.md5(passwd));
    }

    @Override
    public PageInfo<YQContacts> contacts(Long id, String keyWord, Integer pageIndex, Integer pageSize) {
        //不能跨机构使用
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("userId desc");
        if (UserContext.getRole() == UserType.ADMIN || UserContext.getRole() == UserType.GOV || UserContext.getRole() == UserType.GOV_ASS || UserContext.getRole() == UserType.GOV_INP) {
            return new PageInfo<>(mapper.contacts(null, null, null,keyWord));
        }
        YQContacts orgId = mapper.findOrgId(id);
        if (orgId.getOrgId() == null) return new PageInfo<>();

        return new PageInfo<>(mapper.contacts(orgId.getOrgId(), orgId.getBelongInsCode(), orgId.getOrgPid(),keyWord));

    }

    @Override
    public Integer sync() {
        List<YQContacts> sync = mapper.sync();
        JSONArray array = JSONUtil.createArray();
        for (int i = 0; i < sync.size(); i++) {
            YQContacts yqContacts = sync.get(i);
            cn.hutool.json.JSONObject obj = JSONUtil.createObj();
            obj.set("username", "a" + yqContacts.getUserId());
            obj.set("password", "123456");
            obj.set("nickname", yqContacts.getUname());
            array.add(obj);
        }

        JSONArray imUserBatch = emServer.createImUserBatch(array);
        for (int i = 0; i < imUserBatch.size(); i++) {
            JSONObject o = (JSONObject) imUserBatch.get(i);
            mapper.updateEmuid(o.getStr("username").substring(1), o.getStr("uuid"));
        }

        return 1;
    }

}
